package ren.xbcr.schoolbus.client;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.ActionBar;
import android.util.Log;
import android.view.View;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.Marker;
import com.aurelhubert.ahbottomnavigation.AHBottomNavigation;
import com.aurelhubert.ahbottomnavigation.AHBottomNavigationItem;

import java.util.ArrayList;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import ren.xbcr.schoolbus.client.domain.AppInfo;
import ren.xbcr.schoolbus.client.domain.BusDriver;
import ren.xbcr.schoolbus.client.domain.ClientServerSync;
import ren.xbcr.schoolbus.client.domain.LoginUser;
import ren.xbcr.schoolbus.client.domain.transmission.ResponseResult;
import ren.xbcr.schoolbus.client.fragment.CallCarFragment;
import ren.xbcr.schoolbus.client.fragment.ReturnedCallFragment;
import ren.xbcr.schoolbus.client.service.SchoolBusService;
import ren.xbcr.schoolbus.client.service.UpdateService;
import ren.xbcr.schoolbus.client.util.Constants;
import ren.xbcr.schoolbus.client.util.PrefUtils;
import ren.xbcr.schoolbus.client.util.Tool;
import ren.xbcr.schoolbus.client.util.XbcrResult;

public class MainActivity extends AppCompatActivity
        implements LocationSource, AMapLocationListener,
        AMap.OnMarkerClickListener, CallCarFragment.NoticeDialogListener {

    final Handler mHandler = new Handler();
/*    private Runnable mRunnableCode = new Runnable() {
        @Override
        public void run() {
            // Do something here on the main thread
//            Log.d("Handlers", "Called on main thread");
            // Repeat this the same runnable code block again another 2 seconds

            SchoolBusService schoolBusService = new SchoolBusService();
            if (mAMapLocation == null) {
                mHandler.postDelayed(mRunnableCode, 1000);
                return;
            }
            LoginUser loginUser = new LoginUser();
            loginUser.setLatitude(mAMapLocation.getLatitude());
            loginUser.setLongitude(mAMapLocation.getLongitude());
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
//            schoolBusService.sendVerifyCode("13561806126");
//            Tool.setCarsToMap(aMap, cars, markers);
            mHandler.postDelayed(mRunnableCode, 1000);
        }
    };*/

    private Menu mMenu;

    private ScheduledThreadPoolExecutor mSch;
    private AMap aMap;
    private ArrayList<Marker> markers;
    private MapView mapView;
    private AMapLocation mAMapLocation;
    private TextView mLocationErrText;
    private LocationSource.OnLocationChangedListener mListener;
//    private LocationManagerProxy mAMapLocationManager;

    private AMapLocationClient mlocationClient;
    private AMapLocationClientOption mLocationOption;
    private Toolbar mBottomToolbar;

    private Button mMainMapButton;
    private Button mDriverRatingButton;
    private Button mAboutBusinessButton;
    private Button mRecruitDriverButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.app_bar_main);

        new CheckVersionTask(this).execute((Void) null);

//        checkVersion();
        init(savedInstanceState);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
//        actionBar.setDisplayShowTitleEnabled(false);
        actionBar.setIcon(R.mipmap.toolbar_icon);

//        mBottomToolbar = (Toolbar) findViewById(R.id.bottom_toolbar);
//        mBottomActionMenu = (ActionMenuView) mBottomToolbar.findViewById(R.id.bottom_action_menu);
       /* mBottomToolbar.inflateMenu(R.menu.call_car_bottom);//changed
        //toolbar2 menu items CallBack listener
//        mBottomActionMenu.set

        mBottomToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {

            @Override
            public boolean onMenuItemClick(MenuItem arg0) {
                if (arg0.getItemId() == R.id.action_account1) {

                }
                return false;
            }
        });*/

        /*final DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) {
            @Override
            public void onDrawerStateChanged(int newState) {
                if (newState == DrawerLayout.STATE_SETTLING && !drawer.isDrawerOpen(GravityCompat.START) ) {
                    String telephone = PrefUtils.getStringFromPrefs(drawer.getContext(), PrefUtils.PREFS_LOGIN_TELEPHONE, null);
                    if (telephone==null || telephone.isEmpty()){
                        drawer.closeDrawer(GravityCompat.START);
                        Intent intent = new Intent(drawer.getContext(), LoginActivity.class);
                        startActivity(intent);
                    }
                }
            }
        };*/
//        drawer.setDrawerListener(toggle);
        /*toggle.syncState();
        toggle.setToolbarNavigationClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Snackbar.make(v, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });*/
//
//   /*     NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
//        navigationView.setNavigationItemSelectedListener(this);*/
//        AHBottomNavigation bottomNavigation = (AHBottomNavigation) findViewById(R.id.bottom_navigation);
//
//// Create items
//        AHBottomNavigationItem item1 = new AHBottomNavigationItem(R.string.call_car,0, R.color.ForestGreen);
//        AHBottomNavigationItem item2 = new AHBottomNavigationItem(R.string.call_car,0, R.color.ForestGreen);
//        AHBottomNavigationItem item3 = new AHBottomNavigationItem(R.string.call_car,0, R.color.ForestGreen);
//
//// Add items
//        bottomNavigation.addItem(item1);
//        bottomNavigation.addItem(item2);
//        bottomNavigation.addItem(item3);
//
//// Set background color
//        bottomNavigation.setDefaultBackgroundColor(Color.parseColor("#FEFEFE"));
//
//// Disable the translation inside the CoordinatorLayout
//        bottomNavigation.setBehaviorTranslationEnabled(false);
//
//// Change colors
//        bottomNavigation.setAccentColor(Color.parseColor("#F63D2B"));
//        bottomNavigation.setInactiveColor(Color.parseColor("#747474"));
//
//// Force to tint the drawable (useful for font with icon for example)
//        bottomNavigation.setForceTint(true);
//
//// Force the titles to be displayed (against Material Design guidelines!)
//        bottomNavigation.setForceTitlesDisplay(true);
//
//// Use colored navigation with circle reveal effect
//        bottomNavigation.setColored(true);
//
//// Set current item programmatically
//        bottomNavigation.setCurrentItem(1);
//
//// Customize notification (title, background, typeface)
//        bottomNavigation.setNotificationBackgroundColor(Color.parseColor("#F63D2B"));
//
//// Add or remove notification for each item
//        bottomNavigation.setNotification("4", 1);
//        bottomNavigation.setNotification("", 1);
//
//// Set listener
//        bottomNavigation.setOnTabSelectedListener(new AHBottomNavigation.OnTabSelectedListener() {
//            @Override
//            public boolean onTabSelected(int position, boolean wasSelected) {
//                // Do something cool here...
//                return true;
//            }
//        });
        setupBtn();
    }

    private void setupBtn() {

        final FragmentActivity activity = this;
        mMainMapButton = (Button) findViewById(R.id.main_map_button);
        mMainMapButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                /*if (Tool.navToLoginActivity(MainActivity.this, activity)) return;
                Intent intent = new Intent(MainActivity.this, MainActivity.class);

                intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NO_HISTORY);
                startActivity(intent);*/
                /*if (Tool.navToLoginActivity(MainActivity.this, activity)) return;

                DialogFragment dialog = new CallCarFragment();
                dialog.show(getSupportFragmentManager(), "CallCarFragment");*/
            }
        });

        mDriverRatingButton = (Button) findViewById(R.id.driver_rating_btn);
        mDriverRatingButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Tool.navToLoginActivity(MainActivity.this, activity)) return;
                Intent intent = new Intent(MainActivity.this, DriverListActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                startActivity(intent);
            }
        });

        mAboutBusinessButton = (Button) findViewById(R.id.about_business_btn);
        mAboutBusinessButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Tool.navToLoginActivity(MainActivity.this, activity)) return;
                Intent intent = new Intent(MainActivity.this, BusinessCooperationActivity.class);
                intent.setFlags( Intent.FLAG_ACTIVITY_NO_HISTORY);
                startActivity(intent);
            }
        });

        mRecruitDriverButton = (Button) findViewById(R.id.recruit_driver_btn);
        mRecruitDriverButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Tool.navToLoginActivity(MainActivity.this, activity)) return;
                Intent intent = new Intent(MainActivity.this, RecruitDriverActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                startActivity(intent);
            }
        });
    }

    /**
     * 初始化
     */
    private void init(Bundle savedInstanceState) {
        /*
         * 设置离线地图存储目录，在下载离线地图或初始化地图设置;
         * 使用过程中可自行设置, 若自行设置了离线地图存储的路径，
         * 则需要在离线地图下载和使用地图页面都进行路径设置
         * */
        //Demo中为了其他界面可以使用下载的离线地图，使用默认位置存储，屏蔽了自定义设置
//        MapsInitializer.sdcardDir =OffLineMapUtils.getSdCacheDir(this);
        mapView = (MapView) findViewById(R.id.map);
        mapView.onCreate(savedInstanceState);// 此方法必须重写
        if (aMap == null) {
            aMap = mapView.getMap();
        }
        mLocationErrText = (TextView)findViewById(R.id.location_errInfo_text);
        mLocationErrText.setVisibility(View.GONE);

        markers = new ArrayList<Marker>();

        setUpMap();
        /*
        mGPSModeGroup=(RadioGroup) findViewById(R.id.gps_radio_group);
        mGPSModeGroup.setOnCheckedChangeListener(this);*/

    }

    /**
     * 设置一些amap的属性
     */
    private void setUpMap() {

        aMap.moveCamera(CameraUpdateFactory.zoomTo(17));
        aMap.setLocationSource(this);// 设置定位监听

        aMap.getUiSettings().setZoomControlsEnabled(false);
        aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        //设置定位的类型为定位模式 ，可以由定位、跟随或地图根据面向方向旋转几种
        aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);
        aMap.setOnMarkerClickListener(this);
    }

    @Override
    public void onBackPressed() {
//        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
//        if (drawer.isDrawerOpen(GravityCompat.START)) {
//            drawer.closeDrawer(GravityCompat.START);
//        } else {
        super.onBackPressed();
//        }
    }

    /**
     * 检查更新版本
     */
    public void checkVersion() {

        if (Constants.localVersion < Constants.serverVersion) {
            Log.i("hgncxzy", "==============================");
            // 发现新版本，提示用户更新
            AlertDialog.Builder alert = new AlertDialog.Builder(this);
            alert.setTitle("软件升级")
                    .setMessage("发现新版本,建议立即更新使用.")
                    .setPositiveButton("更新",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                                    int which) {
                                    // 开启更新服务UpdateService
                                    // 这里为了把update更好模块化，可以传一些updateService依赖的值
                                    // 如布局ID，资源ID，动态获取的标题,这里以app_name为例
                                    Intent updateIntent = new Intent(
                                            MainActivity.this,
                                            UpdateService.class);
                                    updateIntent.putExtra("titleId",
                                            R.string.app_name);
                                    startService(updateIntent);
                                }
                            })
                    .setNegativeButton("取消",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                                    int which) {
                                    dialog.dismiss();
                                }
                            });
            alert.create().show();
        } else {
            // 清理工作，略去
            // cheanUpdateFile()
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        this.mMenu = menu;
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);

        updateSignMenu();
        return true;
    }

    private void updateSignMenu() {
        String telephone = PrefUtils.getStringFromPrefs(getApplicationContext(), PrefUtils.PREFS_LOGIN_TELEPHONE, null);
        if (telephone == null || telephone.isEmpty()) {
            changeMenuForSignOut();
        } else {
            changeMenuForSignUp();
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.

        // Handle item selection
        switch (item.getItemId()) {
            case R.id.call_car:
                if (Tool.navToLoginActivity(MainActivity.this, this)) return false;

                DialogFragment dialog = new CallCarFragment();
                dialog.show(getSupportFragmentManager(), "CallCarFragment");

                return true;

            case R.id.action_sign_out:
                PrefUtils.removePref(this, PrefUtils.PREFS_LOGIN_TELEPHONE);

                changeMenuForSignOut();
                Context context = getApplicationContext();
                CharSequence text = getString(R.string.sign_out_message);
                int duration = Toast.LENGTH_SHORT;

                Toast toast = Toast.makeText(context, text, duration);
                toast.show();

                break;
            case R.id.action_sign_up:
                Tool.navToLoginActivity(MainActivity.this, this);
                break;
            default:
                return super.onOptionsItemSelected(item);
        }
        return true;

    }

    private void changeMenuForSignOut() {
        if (mMenu == null) {
            return;
        }
        MenuItem signUpItem = mMenu.findItem(R.id.action_sign_up);
        signUpItem.setVisible(true);
        MenuItem signOutItem = mMenu.findItem(R.id.action_sign_out);
        signOutItem.setVisible(false);
    }

    private void changeMenuForSignUp() {
        if (mMenu == null) {
            return;
        }
        MenuItem signUpItem = mMenu.findItem(R.id.action_sign_up);
        signUpItem.setVisible(false);
        MenuItem signOutItem = mMenu.findItem(R.id.action_sign_out);
        signOutItem.setVisible(true);
    }
/*
    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_driver_rating) {
            Intent intent = new Intent(this, DriverListActivity.class);
            startActivity(intent);
        } else if (id == R.id.nav_business_cooperation) {
            Intent intent = new Intent(this, BusinessCooperationActivity.class);
            startActivity(intent);
        } else if (id == R.id.nav_recruit_driver) {
            Intent intent = new Intent(this, RecruitDriverActivity.class);
            startActivity(intent);
        } else if (id == R.id.sign_out) {
            PrefUtils.removePref(this, PrefUtils.PREFS_LOGIN_TELEPHONE);
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }*/


    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
//        mHandler.post(mRunnableCode);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
//        mHandler.removeCallbacks(mRunnableCode);
        deactivate();
    }

    @Override
    protected void onStart() {
        super.onStart();

        mSch = (ScheduledThreadPoolExecutor)
                Executors.newScheduledThreadPool(5);
        ScheduledFuture<?> periodicFuture = mSch.scheduleAtFixedRate(new ServerSyncTask(this), 0, 5, TimeUnit.SECONDS);
    }

    @Override
    protected void onStop() {
        super.onStop();
        mSch.shutdown();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
        if(null != mlocationClient){
            mlocationClient.onDestroy();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // Check which request it is that we're responding to
        if (requestCode == Tool.LOGIN_REQUEST) {
            updateSignMenu();
            // Make sure the request was successful
            if (resultCode == RESULT_OK) {
            }
        }
    }

    /**
     * 激活定位
     */
    @Override
    public void activate(OnLocationChangedListener listener) {


/*
        final String[] locationPermissions = new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION};
        final String[] storagePermissions = new String[]{
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.READ_PHONE_STATE};

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(this, locationPermissions, 0);
        }

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(this, storagePermissions, 0);
        }*/

        mListener = listener;

        if (mlocationClient == null) {
            mlocationClient = new AMapLocationClient(this);
            mLocationOption = new AMapLocationClientOption();
            //设置定位监听
            mlocationClient.setLocationListener(this);
            //设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置定位参数
            mlocationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            mlocationClient.startLocation();
        }

        /*if (mAMapLocationManager == null) {
            mAMapLocationManager = LocationManagerProxy.getInstance(this);
            *//*
             * mAMapLocManager.setGpsEnable(false);
			 * 1.0.2版本新增方法，设置true表示混合定位中包含gps定位，false表示纯网络定位，默认是true Location
			 * API定位采用GPS和网络混合定位方式
			 * ，第一个参数是定位provider，第二个参数时间最短是2000毫秒，第三个参数距离间隔单位是米，第四个参数是定位监听者
			 *//*
            mAMapLocationManager.requestLocationData(
                    LocationProviderProxy.AMapNetwork, 2000, 10, this);
        }*/

//        mLocationTask.startLocate(listener);
    }

    /**
     * 停止定位
     */
    @Override
    public void deactivate() {
        mListener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
//        mLocationTask.onDestroy();
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {

        if (mListener != null && aMapLocation != null) {
            if (aMapLocation != null
                    && aMapLocation.getErrorCode() == 0) {
                mLocationErrText.setVisibility(View.GONE);
                mListener.onLocationChanged(aMapLocation);// 显示系统小蓝点
                mAMapLocation = aMapLocation;
            } else {
                String errText = "定位失败," + aMapLocation.getErrorCode()+ ": " + aMapLocation.getErrorInfo();
                Log.e("AmapErr",errText);
                mLocationErrText.setVisibility(View.VISIBLE);
                mLocationErrText.setText(errText);
            }
        }

       /* if (aMapLocation != null && aMapLocation.getAMapException() != null
                && aMapLocation.getAMapException().getErrorCode() == 0) {
            mListener.onLocationChanged(aMapLocation);// 显示系统小蓝点
            mAMapLocation = aMapLocation;

            *//*LatLng ll = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());
            Utils.addEmulateData(aMap, ll);*//*

        }*/
    }

    @Override
    public boolean onMarkerClick(Marker marker) {
//        marker.destroy();
        return true;
    }

    @Override
    public void onDialogConfirmClick(DialogFragment dialog) {


        if (mAMapLocation == null) {
            Tool.showToast(this, getString(R.string.error_location_call_car));
            return;
        }
        LoginUser loginUser = new LoginUser();

        loginUser.setLatitude(mAMapLocation.getLatitude());
        loginUser.setLongitude(mAMapLocation.getLongitude());

        String telephone = PrefUtils.getStringFromPrefs(this, PrefUtils.PREFS_LOGIN_TELEPHONE, null);
        if (telephone == null || telephone.isEmpty()) {

            Tool.showToast(this, getString(R.string.error_login_call_car));
            return;
        }
        loginUser.setTelephoneNumber(telephone);
        CallCarTask callCarTask = new CallCarTask(this, loginUser);
        callCarTask.execute((Void) null);

    }

    @Override
    public void onDialogCancelClick(DialogFragment dialog) {

    }

    private class ServerSyncTask implements Runnable {

        private Context mContext;

        public ServerSyncTask(Context context) {
            this.mContext = context;
        }

        @Override
        public void run() {

            SchoolBusService schoolBusService = new SchoolBusService();
            if (mAMapLocation == null) {
//                mHandler.postDelayed(mRunnableCode, 1000);
                return;
            }
            LoginUser loginUser = new LoginUser();
            loginUser.setLatitude(mAMapLocation.getLatitude());
            loginUser.setLongitude(mAMapLocation.getLongitude());

            String telephone = PrefUtils.getStringFromPrefs(mContext, PrefUtils.PREFS_LOGIN_TELEPHONE, null);
            if (telephone == null || telephone.isEmpty()) {
                return;
            }
            loginUser.setTelephoneNumber(telephone);
            ClientServerSync clientServerSync = schoolBusService.clientSyncServer(loginUser);

            for (BusDriver busDriver :
                    clientServerSync.getBusDrivers()) {

                if (busDriver.getIsAccepted() != null && busDriver.getIsAccepted()) {
                    DialogFragment dialog = ReturnedCallFragment.newInstance(busDriver.getDriveCar().getCode());
                    dialog.show(getSupportFragmentManager(), "ReturnedCallFragment");
                    break;
                }
            }

            Tool.setCarsToMap(aMap, new ArrayList<BusDriver>(clientServerSync.getBusDrivers()), markers);
//            mHandler.postDelayed(mRunnableCode, 1000);
        }
    }

    private class CallCarTask extends AsyncTask<Void, Void, ResponseResult> {

        private LoginUser mLoginUser;
        private Context mContext;

        public CallCarTask(Context context, LoginUser loginUser) {
            mContext = context;
            mLoginUser = loginUser;
        }

        @Override
        protected ResponseResult doInBackground(Void... params) {
            // TODO: attempt authentication against a network service.
            Boolean isLoginSuccess = false;
            // Simulate network access.
            SchoolBusService schoolBusService = new SchoolBusService();
            ResponseResult responseResult = schoolBusService.callCar(mLoginUser);

            return responseResult;
        }

        @Override
        protected void onPostExecute(final ResponseResult result) {

            if (result.getResultCode() == XbcrResult.RESULT_SUCCESS) {
                Tool.showToast(mContext, getString(R.string.success_call_car_message));
            } else {

                Tool.showToast(mContext, getString(R.string.error_call_car_message));
            }


        }
    }

    private class CheckVersionTask extends AsyncTask<Void, Void, AppInfo> {

        private Context mContext;

        public CheckVersionTask(Context context) {
            mContext = context;
        }

        @Override
        protected AppInfo doInBackground(Void... params) {
            // TODO: attempt authentication against a network service.
            Boolean isLoginSuccess = false;
            // Simulate network access.
            SchoolBusService schoolBusService = new SchoolBusService();
            AppInfo appInfo = schoolBusService.getVersionCode();

            return appInfo;
        }

        @Override
        protected void onPostExecute(final AppInfo result) {
            Constants.serverVersion = result.getVersionCode();// 假定服务器版本为2，本地版本默认是1--实际开发中是从服务器获取最新版本号，android具体与后端的交互见我另///外的博文
            Constants.downloadUrl = result.getAppUrl();
            checkVersion();
        }
    }

}
